﻿using System;
using System.IO;
using System.Net;
using System.Reflection;
using System.Text;
using AutoTAU.Properties;

namespace AutoTAU
{
    internal static class StatsManager
    {
        /// <summary>
        /// Count failures
        /// </summary>
        private static uint FailureCounter;

        /// <summary>
        /// Start the statistics manager
        /// </summary>
        /// <returns>Whether stats need to be submitted</returns>
        public static void Start()
        {
            try
            {
                if (!SubmitStats())
                {
                    // Failed, perhaps because we're offline. Try again when we're online.
                    WifiAuthManager.WifiAuthEvent += StatsWifiEventHandler;
                }
            }

                // Ignore all errors
            catch
            {
            }
        }

        /// <summary>
        /// Submit information about this installation to the statistics server
        /// </summary>
        /// <returns>Whether stats were submitted successfully</returns>
        private static bool SubmitStats()
        {
            try
            {
                var postRequest = (HttpWebRequest) WebRequest.Create("http://autotau-statistics.appspot.com");
                postRequest.KeepAlive = false;
                postRequest.ContentType = "application/x-www-form-urlencoded";
                postRequest.Method = "POST";
                byte[] postBytes =
                    Encoding.ASCII.GetBytes(
                        String.Format(
                            "version={0}",
                            Assembly.GetExecutingAssembly().GetName().Version));
                postRequest.ContentLength = postBytes.Length;
                Stream postStream = postRequest.GetRequestStream();
                postStream.Write(postBytes, 0, postBytes.Length);
                postRequest.GetResponse().GetResponseStream();

                // Stats submitted successfully, don't resubmit next time
                Settings.Default.LastReportedInstallation = Assembly.GetExecutingAssembly().GetName().Version.ToString();
                Settings.Default.Save();
            }
            
                // Catch all exceptions (no specific error handling is possible here anyway)
            catch
            {
                // Failed to submit stats
                return false;
            }

            // Stats submitted successfully
            return true;
        }

        private static void StatsWifiEventHandler(WifiStatus status, string title, string msg, bool critical)
        {
            if ((status == WifiStatus.Success) || (status == WifiStatus.ConnectedToAnotherNetwork))
            {
                // Try to submit stats
                if (SubmitStats())
                {
                    // Success, unregister this handler
                    WifiAuthManager.WifiAuthEvent -= StatsWifiEventHandler;
                }
                
                    // Failed to submit stats
                else
                {
                    // Increment failure counter
                    FailureCounter += 1;
                    if (FailureCounter >= 10)
                    {
                        // Too many failures, there must be something wrong. Stop trying.
                        WifiAuthManager.WifiAuthEvent -= StatsWifiEventHandler;
                    }
                }
            }
        }
    }
}